﻿// /* **********************************************************************************
//  *
//  * Copyright (c) Sky Sanders. All rights reserved.
//  * 
//  * This source code is subject to terms and conditions of the Microsoft Public
//  * License (Ms-PL). A copy of the license can be found in the license.htm file
//  * included in this distribution.
//  *
//  * You must not remove this notice, or any other, from this software.
//  *
//  * **********************************************************************************/
using System;
using System.Text;
using System.Web;
using System.Web.UI;
using Newtonsoft.Json;
using SimpleRemoteControl.Data.Repositories;

namespace SimpleRemoteControl
{
    public class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bool dataResponse = false;

            StringBuilder output = new StringBuilder();
            Common.Config.Address = string.IsNullOrEmpty(Common.Config.Address)
                                        ? Request.Url.Authority
                                        : Common.Config.Address;

            object outputObj = null;
            try
            {
                if (Request["list"] != null || Request.Url.ToString().ToLower().EndsWith("list"))
                {
                    outputObj = ServerRepository.GetServer();
                    dataResponse = true;
                }
                else if (!string.IsNullOrEmpty(Request["open"]))
                {
                    outputObj = BrowserControl.Open(Request["open"]);
                    dataResponse = true;
                }
                else if (!string.IsNullOrEmpty(Request["close"]))
                {
                    outputObj = BrowserControl.Close(Request["close"]);
                    dataResponse = true;
                }
            }
            catch (Exception ex)
            {
                outputObj = new Exception("Error processing request.", ex);
                dataResponse = true;
            }

            if (!dataResponse)
            {
                // just display the usage page
                return;
            }

            JsonSerializerSettings s = new JsonSerializerSettings();
            if (outputObj is Exception)
            {
                // swallow self referencing exceptions 
                s.Error += ((obj, args) =>
                {
                    args.ErrorContext.Handled = true;
                });
            }

            output.Append(JsonConvert.SerializeObject(outputObj, Formatting.Indented, s));

            InitializeDataResponse();
            Response.Write(output.ToString());
            Response.Flush();
            Response.End();
        }

        /// <summary>
        /// Ensures that data is served in a format understood by the client
        /// and that all efforts are made to prevent caching of JSON.
        /// </summary>
        private void InitializeDataResponse()
        {
            if (Request.ContentType.StartsWith("text/json"))
            {
                Response.ContentType = "text/json";
            }
            else if (Request.ContentType.StartsWith("application/json"))
            {
                Response.ContentType = "application/json";
            }
            else
            {
                Response.ContentType = "text/plain";
            }


            Response.AddHeader("content-disposition", "inline");
            Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
        }
    }
}